package com.qf.shixi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qf.shixi.dao.SysUserDao;
import com.qf.shixi.entity.SysUser;
import com.qf.shixi.exception.BusinessException;
import com.qf.shixi.result.ResponseCode;
import com.qf.shixi.service.SysUserService;
import com.qf.shixi.util.Md5Util;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * (SysUser)表服务实现类
 *
 * @author
 * @since 2021-10-17 23:01:54
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserDao sysUserDao;

    @Value("wxef56c9e9b6ef21d2")
    private String appid;

    @Value("464e79ec837a6580f09a6d4bb6dc48ec")
    private String secret;

    @Override
    public String wxLogin(String code) throws IOException {
        // 设置请求地址
        String url = "GET https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        // 创建一个get请求
        HttpGet httpGet = new HttpGet(url);
        // 创建客户端
        CloseableHttpClient client = HttpClients.createDefault();  //one exception
        // 通过客户端发送请求
        CloseableHttpResponse response = client.execute(httpGet);
        // 获取响应中的数据
        HttpEntity entity = response.getEntity();
        // 将entity数据转换为json字符串
        String s = EntityUtils.toString(entity);
        System.out.println(s);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String session_key = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");
        //自定义登陆状态 --token (token先放在mysql数据库中--后续放在redis)
        // md5进行加密数据 生成token
        Md5Hash md5Hash = new Md5Hash(openid,session_key,1000);
        String token = md5Hash.toString();
        SysUser sysUser1 = sysUserDao.queryByOpenId(openid);
        if(sysUser1 == null){
            SysUser sysUser = new SysUser();
            sysUser.setOpenid(openid);
            sysUser.setSessionkey(session_key);
            sysUser.setToken(token);
            sysUserDao.insert(sysUser);
        }else{
            sysUser1.setOpenid(openid);
            sysUser1.setSessionkey(session_key);
            sysUser1.setToken(token);
            sysUserDao.update(sysUser1);
        }
        return token;

    }

    @Override
    public SysUser sysLogin(SysUser sysUser) {
        //通过用户名去数据库中查找用户
        SysUser sysUser1 = sysUserDao.queryByName(sysUser.getUname());
        if(sysUser1 == null){
            throw new BusinessException(ResponseCode.AUTH_EXCEPTION.getCode(),ResponseCode.AUTH_EXCEPTION.getMessage());
        }
        String  pwd = Md5Util.getSys(sysUser.getUname(),sysUser.getPassword());
        if(!sysUser1.getPassword().equals(pwd)){
            throw new BusinessException(ResponseCode.AUTH_EXCEPTION.getCode(),ResponseCode.AUTH_EXCEPTION.getMessage());
        }

        String token = UUID.randomUUID().toString();
        sysUser1.setSystoken(token);
        sysUserDao.update(sysUser1);
//      将登陆成功的消息返回给前端
        sysUser.setPassword("");
//        存放在redis
        sysUser.setSystoken(token);
        return sysUser;





    }

    @Override
    public SysUser queryBySysToken(String token) {
        return sysUserDao.queryBySysToken(token);
    }

    @Override
    public SysUser queryByToken(String token) {
        return sysUserDao.queryByToken(token);
    }


    /**
     * 通过ID查询单条数据
     *
     * @param uId 主键
     * @return 实例对象
     */
    @Override
    public SysUser queryById(Integer uId) {
        return this.sysUserDao.queryById(uId);
    }



    /**
     * 新增数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public SysUser insert(SysUser sysUser) {
        this.sysUserDao.insert(sysUser);
        return sysUser;
    }

    /**
     * 修改数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public Boolean update(SysUser sysUser) {
        SysUser sysUser1 = new SysUser();
        sysUser1.setToken(sysUser.getToken());
        List<SysUser> sysUsers = sysUserDao.queryAllByConditions(sysUser1);
        Integer update = 0;
        Integer insert = 0;
        if(sysUsers.size() == 1){
            sysUser.setuId(sysUsers.get(0).getuId());
            update = sysUserDao.update(sysUser);
            System.out.println(update+"-------");
        }else{
             insert = sysUserDao.insert(sysUser);
        }
        if( update > 0 || insert>0 ){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 通过主键删除数据
     *
     * @param uId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer uId) {
        return this.sysUserDao.deleteById(uId) > 0;
    }


}
